/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package entidade.controller.JPA;

import entidade.controller.JPA.exceptions.IllegalOrphanException;
import entidade.controller.JPA.exceptions.NonexistentEntityException;
import entidade.controller.JPA.exceptions.RollbackFailureException;
import entidade.persistencia.AreaAtuacao;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import entidade.persistencia.Empresa;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.UserTransaction;

/**
 *
 * @author victorinox
 */
public class AreaAtuacaoJpaController {
    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "globalimage2PU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(AreaAtuacao areaAtuacao) throws RollbackFailureException, Exception {
        if (areaAtuacao.getEmpresaCollection() == null) {
            areaAtuacao.setEmpresaCollection(new ArrayList<Empresa>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<Empresa> attachedEmpresaCollection = new ArrayList<Empresa>();
            for (Empresa empresaCollectionEmpresaToAttach : areaAtuacao.getEmpresaCollection()) {
                empresaCollectionEmpresaToAttach = em.getReference(empresaCollectionEmpresaToAttach.getClass(), empresaCollectionEmpresaToAttach.getEmpresaId());
                attachedEmpresaCollection.add(empresaCollectionEmpresaToAttach);
            }
            areaAtuacao.setEmpresaCollection(attachedEmpresaCollection);
            em.persist(areaAtuacao);
            for (Empresa empresaCollectionEmpresa : areaAtuacao.getEmpresaCollection()) {
                AreaAtuacao oldAreaAtuacaoIdOfEmpresaCollectionEmpresa = empresaCollectionEmpresa.getAreaAtuacaoId();
                empresaCollectionEmpresa.setAreaAtuacaoId(areaAtuacao);
                empresaCollectionEmpresa = em.merge(empresaCollectionEmpresa);
                if (oldAreaAtuacaoIdOfEmpresaCollectionEmpresa != null) {
                    oldAreaAtuacaoIdOfEmpresaCollectionEmpresa.getEmpresaCollection().remove(empresaCollectionEmpresa);
                    oldAreaAtuacaoIdOfEmpresaCollectionEmpresa = em.merge(oldAreaAtuacaoIdOfEmpresaCollectionEmpresa);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(AreaAtuacao areaAtuacao) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            AreaAtuacao persistentAreaAtuacao = em.find(AreaAtuacao.class, areaAtuacao.getAreaAtuacaoId());
            List<Empresa> empresaCollectionOld = persistentAreaAtuacao.getEmpresaCollection();
            List<Empresa> empresaCollectionNew = areaAtuacao.getEmpresaCollection();
            List<String> illegalOrphanMessages = null;
            for (Empresa empresaCollectionOldEmpresa : empresaCollectionOld) {
                if (!empresaCollectionNew.contains(empresaCollectionOldEmpresa)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Empresa " + empresaCollectionOldEmpresa + " since its areaAtuacaoId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Empresa> attachedEmpresaCollectionNew = new ArrayList<Empresa>();
            for (Empresa empresaCollectionNewEmpresaToAttach : empresaCollectionNew) {
                empresaCollectionNewEmpresaToAttach = em.getReference(empresaCollectionNewEmpresaToAttach.getClass(), empresaCollectionNewEmpresaToAttach.getEmpresaId());
                attachedEmpresaCollectionNew.add(empresaCollectionNewEmpresaToAttach);
            }
            empresaCollectionNew = attachedEmpresaCollectionNew;
            areaAtuacao.setEmpresaCollection(empresaCollectionNew);
            areaAtuacao = em.merge(areaAtuacao);
            for (Empresa empresaCollectionNewEmpresa : empresaCollectionNew) {
                if (!empresaCollectionOld.contains(empresaCollectionNewEmpresa)) {
                    AreaAtuacao oldAreaAtuacaoIdOfEmpresaCollectionNewEmpresa = empresaCollectionNewEmpresa.getAreaAtuacaoId();
                    empresaCollectionNewEmpresa.setAreaAtuacaoId(areaAtuacao);
                    empresaCollectionNewEmpresa = em.merge(empresaCollectionNewEmpresa);
                    if (oldAreaAtuacaoIdOfEmpresaCollectionNewEmpresa != null && !oldAreaAtuacaoIdOfEmpresaCollectionNewEmpresa.equals(areaAtuacao)) {
                        oldAreaAtuacaoIdOfEmpresaCollectionNewEmpresa.getEmpresaCollection().remove(empresaCollectionNewEmpresa);
                        oldAreaAtuacaoIdOfEmpresaCollectionNewEmpresa = em.merge(oldAreaAtuacaoIdOfEmpresaCollectionNewEmpresa);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = areaAtuacao.getAreaAtuacaoId();
                if (findAreaAtuacao(id) == null) {
                    throw new NonexistentEntityException("The areaAtuacao with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            AreaAtuacao areaAtuacao;
            try {
                areaAtuacao = em.getReference(AreaAtuacao.class, id);
                areaAtuacao.getAreaAtuacaoId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The areaAtuacao with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Empresa> empresaCollectionOrphanCheck = areaAtuacao.getEmpresaCollection();
            for (Empresa empresaCollectionOrphanCheckEmpresa : empresaCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This AreaAtuacao (" + areaAtuacao + ") cannot be destroyed since the Empresa " + empresaCollectionOrphanCheckEmpresa + " in its empresaCollection field has a non-nullable areaAtuacaoId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(areaAtuacao);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<AreaAtuacao> findAreaAtuacaoEntities() {
        return findAreaAtuacaoEntities(true, -1, -1);
    }

    public List<AreaAtuacao> findAreaAtuacaoEntities(int maxResults, int firstResult) {
        return findAreaAtuacaoEntities(false, maxResults, firstResult);
    }

    private List<AreaAtuacao> findAreaAtuacaoEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from AreaAtuacao as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public AreaAtuacao findAreaAtuacao(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(AreaAtuacao.class, id);
        } finally {
            em.close();
        }
    }

    public int getAreaAtuacaoCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from AreaAtuacao as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
